const pageHelper = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getRootConfigPath('project_helpers_config.js').(_, __, helper) => helper.replace('.js', '');
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { teamStore } = require('../config/path_resolver').getRootConfigPath('path_resolver.js').getRootConfigPath('path_resolver.js').getProjectStorePath('modules/team_store.js');
const Day = require('dayjs');
const { logEvent } = require('../../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../../helpers/network_helper.js');

Page({
  data: {
    projectId: '',
    memberId: '',
    memberName: '',
    memberRole: '',
    roleText: '',
    joinTime: '',
    
    // 权限配置
    permissions: {
      project: { read: false, write: false, delete: false, admin: false },
      task: { read: false, write: false, delete: false, assign: false },
      document: { read: false, write: false, delete: false, approve: false },
      member: { read: false, write: false, delete: false, assign: false }
    },
    
    // 权限分组
    permissionGroups: [
      {
        name: 'project',
        title: '项目权限',
        items: [
          { key: 'read', label: '查看项目' },
          { key: 'write', label: '编辑项目' },
          { key: 'delete', label: '删除项目' },
          { key: 'admin', label: '项目管理员' }
        ]
      },
      {
        name: 'task',
        title: '任务权限',
        items: [
          { key: 'read', label: '查看任务' },
          { key: 'write', label: '编辑任务' },
          { key: 'delete', label: '删除任务' },
          { key: 'assign', label: '分配任务' }
        ]
      },
      {
        name: 'document',
        title: '文档权限',
        items: [
          { key: 'read', label: '查看文档' },
          { key: 'write', label: '上传文档' },
          { key: 'delete', label: '删除文档' },
          { key: 'approve', label: '审批文档' }
        ]
      },
      {
        name: 'member',
        title: '团队权限',
        items: [
          { key: 'read', label: '查看成员' },
          { key: 'write', label: '添加/编辑成员' },
          { key: 'delete', label: '移除成员' },
          { key: 'assign', label: '分配工作量' }
        ]
      }
    ],
    
    // 预设权限模板
    permissionTemplates: [
      { name: '项目负责人', role: 'leader' },
      { name: '项目经理', role: 'manager' },
      { name: '团队成员', role: 'member' },
      { name: '只读权限', role: 'readonly' }
    ],
    
    // 页面状态
    hasChanged: false,
    submitting: false
  },
  
  onLoad: async function(options) {
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'plm_team_permission' });
    
    // 创建MobX绑定
    this.storeBindings = createStoreBindings(this, {
      store: teamStore,
      fields: ['loading', 'error', 'currentMember'],
      actions: ['getTeamMemberDetail', 'updateMemberPermissions']
    });
    
    if (options.id && options.projectId) {
      this.setData({
        memberId: options.id,
        projectId: options.projectId
      });
      
      // 加载成员详情
      this.getTeamMemberDetail(options.id).then(() => {
        if (this.data.currentMember) {
          this._updateMemberInfo();
        } else {
          pageHelper.showErrorToast('未找到团队成员信息');
          setTimeout(() => wx.navigateBack(), 1500);
        }
      }).catch(err => {
        pageHelper.showErrorToast('加载失败：' + err.message);
      });
    } else {
      pageHelper.showErrorToast('参数错误');
      setTimeout(() => wx.navigateBack(), 1500);
    }
  },
  
  // 更新成员信息到页面
  _updateMemberInfo: function() {
    const member = this.data.currentMember;
    
    this.setData({
      memberName: member.userName,
      memberRole: member.role,
      roleText: member.getRoleDisplay(),
      joinTime: Day(member.joinTime).format('YYYY-MM-DD'),
      permissions: member.permissions || {
        project: { read: false, write: false, delete: false, admin: false },
        task: { read: false, write: false, delete: false, assign: false },
        document: { read: false, write: false, delete: false, approve: false },
        member: { read: false, write: false, delete: false, assign: false }
      }
    });
  },
  
  // 切换单个权限
  onPermissionChange: function(e) {
    const { module, key } = e.currentTarget.dataset;
    const value = e.detail.value;
    
    // 更新权限设置
    const permissions = this.data.permissions;
    permissions[module][key] = value;
    
    this.setData({
      permissions,
      hasChanged: true
    });
  },
  
  // 应用权限模板
  onApplyTemplate: function(e) {
    const role = e.currentTarget.dataset.role;
    const teamMember = new TeamMemberModel({ role }); // 临时创建成员模型以获取默认权限
    
    this.setData({
      permissions: teamMember.getDefaultPermissions(role),
      hasChanged: true
    });
  },
  
  // 保存权限设置
  savePermissions: function() {
    if (this.data.submitting) return;
    
    this.setData({ submitting: true });
    
    // 调用Store方法保存权限
    this.updateMemberPermissions(
      this.data.memberId,
      this.data.projectId,
      this.data.permissions
    ).then(() => {
      pageHelper.showSuccessToast('权限设置已保存');
      this.setData({
        hasChanged: false,
        submitting: false
      });
      
      // 返回上一页
      setTimeout(() => wx.navigateBack(), 1500);
    }).catch(err => {
      pageHelper.showErrorToast('保存失败：' + err.message);
      this.setData({ submitting: false });
    });
  },
  
  // 重置权限设置
  resetPermissions: function() {
    // 重新载入成员信息
    this.getTeamMemberDetail(this.data.memberId).then(() => {
      if (this.data.currentMember) {
        this._updateMemberInfo();
        this.setData({ hasChanged: false });
      }
    });
  },
  
  onUnload: function() {
    // 销毁MobX绑定
    this.storeBindings.destroyStoreBindings();
  }
}); 